#include "savedgameslist.h"

SavedGamesList::SavedGamesList()
{
    savePath = ".";
    maxId = 0;
}


SavedGame *SavedGamesList::getSavedGameAt(int pos) {return m_savedGames.at(pos);}
int SavedGamesList::getCount() {return this->m_savedGames.count();}

int SavedGamesList::addSavedGame(QString saveName, QStringList &levels, int levelPos)
{
    SavedGame *savedGame = new SavedGame(saveName, maxId++, levels, levelPos);
    m_savedGames.append(savedGame);

    return maxId-1;
}

int SavedGamesList::replaceSavedGame(int pos, QString saveName, QStringList &levels, int levelPos)
{
    int id = m_savedGames.at(pos)->getSaveId();
    SavedGame *savedGame = new SavedGame(saveName, id, levels, levelPos);

    delete m_savedGames.at(pos);
    m_savedGames.replace(pos, savedGame);

    return id;
}

int SavedGamesList::removeSavedGame(int pos)
{
    QString savePath = ".";
    int id = getSavedGameAt(pos)->getSaveId();

    QFile::remove("save" + QString::number(id)); //on supprime le fichier de sauvegarde
    delete m_savedGames.at(pos); //on supprime la sauvegarde de la memoire
    m_savedGames.removeAt(pos); //on supprime la sauvegarde de la liste

    writeToFile(savePath + "/" + "gameslist");
    return id;
}


void SavedGamesList::writeToFile(QString fileName)
{
    QFile file(fileName);
    file.open(QIODevice::WriteOnly);
    QDataStream out(&file);

    out << (qint32)maxId;
    out << (qint32)getCount();

    foreach(SavedGame *savedGame, m_savedGames)
        out << savedGame;

    file.close();
}

void SavedGamesList::readFromFile(QString filePath)
{
    QFile file(filePath);
    if(!file.open(QIODevice::ReadOnly)) return;
    QDataStream in(&file);
    SavedGame *savedGame;
    int n;

    in >> maxId;
    in >> n;

    for(int i = 0; i < n; i++)
    {
        savedGame = new SavedGame();
        in >> savedGame;
        m_savedGames.append(savedGame);
    }

    file.close();
}



